package sivin.uikit.dialog

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.DialogFragment
import androidx.viewbinding.ViewBinding
import sivin.uikit.R

open class BaseBindingDialog<B : ViewBinding>(
    private val inflater: (LayoutInflater) -> B
) : AppCompatDialogFragment() {

    protected val binding: B by lazy {
        inflater(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //背景Window设置透明
        val style = if (expandFullScreen()) {
            R.style.FullscreenDialogTheme
        } else {
            R.style.NormalDialogTheme
        }
        setStyle(DialogFragment.STYLE_NORMAL, style)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return binding.root
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.let { window ->
            if (expandFullScreen()) {
                // 设置宽高填充屏幕
                window.setLayout(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
                // 设置延伸到状态栏
                window.setFlags(
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
                )
            } else {
                //设置是否需要Dialog的阴影
                window.setDimAmount(if (needDim()) 1.0f else 0.0f)
                val params = window.attributes
                params.width = resources.displayMetrics.widthPixels
                params.height = resources.displayMetrics.heightPixels
                window.attributes = params
            }
        }
        dialog?.setCancelable(cancelable())
    }

    //是否需要Dialog的阴影
    open fun needDim(): Boolean = true

    //Dialog是否能取消
    open fun cancelable() = true

    /*
        Dialog的内容是否延伸到整个屏幕，包括操作栏和整个状态栏
        一般不常使用
     */
    open fun expandFullScreen() = false
}